package tony.com.xframe.network;

import android.content.Context;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import java.util.HashMap;
import java.util.Map;

/**
 * 简单的二次封装volley
 * Created by Tony on 2015-12-31.
 */
public class VolleyUtil extends Volley {
    public static VolleyUtil volleyUtil;

    public static VolleyUtil getIntance() {
        if (volleyUtil == null) {
            volleyUtil = new VolleyUtil();
        }
        return volleyUtil;
    }

    RequestQueue requestQueue;

    public void getNetResult(Context context, String url, String tag, final VolleyListener volleyListener, final Map<String, String> map) {
        requestQueue = Volley.newRequestQueue(context);
        //取消之前的请求
        requestQueue.cancelAll(tag);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                volleyListener.onSuccess(s);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                volleyListener.onFailure(volleyError);
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {

                if(map==null){
                   return new HashMap<String,String>();
                }
                return map;
            }
        };
        requestQueue.add(stringRequest);
    }
}
